<?php

namespace app\common\model;

use think\Model;

class User extends Model
{
    const PREFIX_KEY = "eco_member";
	// 完整数据表名
	protected $table = 'user';
	
	// 验证葡萄数 增加 jlc 与 算力
	public function checkGrapes($id) 
	{	
		$user = $this->get($id);
		// jlc
		if ($user['grapes_jlc'] >= sysconf('grapes_num')) {
			$user->where(['id'=>$id])
			->dec('grapes_jlc',sysconf('grapes_num'))
			->inc('jlc',sysconf('jlc_num'))
			->update();
		}
		// 算力
		$floor = floor($user['grapes_calculation']);
		if ($floor > 0) {
			$user->where(['id'=>$id])
			->dec('grapes_calculation',$floor)
			->inc('calculation',$floor)
			->update();
		}
	}

	// 获取单条用户信息
	public function getUser($val,$field = 'id')
	{	
		return $this->where([$field=>$val])->whereOr('id',$val)->find();
	}
	// 插入用户数据
	public function addUser($data) 
	{
        $add_data['mobile'] = $data['mobile'];
        $add_data['password'] = md5(md5(self::PREFIX_KEY . $data['pass']));
        if (!empty($data['recommend_mobile'])) $add_data['recommend_mobile'] = $data['recommend_mobile'];
        $add_data['nick_name'] = $data['mobile'];
        $add_data['calculation'] = sysconf('calculation');
        $add_data['register_time'] = time();
        $add_data['register_ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
        $add_data['create_time'] = time();
        $add_data['create_date'] = date('Y-m-d');



        $res = $this->save($add_data);
        if (!$res) return $res;
		$get_user = $this->getUser($data['mobile'],'mobile');
		unset($get_user['pass']);
		return $get_user;
	}
}